package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.AdminAddressProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private AdminAddressProperties adminAddressProperties;

    private static final Integer maxDistance = 5000;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理各种业务异常（地址簿不存在，购物车数据为空）TODO 后续会加入用户收货地址距离与商家距离相差过远的异常处理
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserId(userId);
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 计算商家的位置经纬度
        Map<String, String> mapAdmin = new HashMap<>();
        mapAdmin.put("address", adminAddressProperties.getAddress());
        mapAdmin.put("output", adminAddressProperties.getOutput());
        mapAdmin.put("ak", adminAddressProperties.getAk());
        String adminPointJson = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", mapAdmin);
        JSONObject adminPointJsonObject = JSONObject.parseObject(adminPointJson);
        double lngAdmin =  adminPointJsonObject.getJSONObject("result").getJSONObject("location").getDouble("lng");
        double latAdmin =  adminPointJsonObject.getJSONObject("result").getJSONObject("location").getDouble("lat");

        // 计算收货人的位置经纬度
        Map<String, String> mapUser = new HashMap<>();
        mapUser.put("address", addressBook.getDetail());
        mapUser.put("output", adminAddressProperties.getOutput());
        mapUser.put("ak", adminAddressProperties.getAk());
        String userPointJson = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", mapUser);
        JSONObject userPointJsonObject = JSONObject.parseObject(userPointJson);
        double lngUser = userPointJsonObject.getJSONObject("result").getJSONObject("location").getDouble("lng");
        double latUser = userPointJsonObject.getJSONObject("result").getJSONObject("location").getDouble("lat");

        // 基于百度地图路径规划api计算商家与收货人地址之间的距离，大于5km则下单失败
        Map<String, String> mapRiding = new HashMap<>();
        mapRiding.put("origin", latAdmin + "," + lngAdmin);
        mapRiding.put("destination", latUser + "," + lngUser);
        mapRiding.put("ak", adminAddressProperties.getAk());
        String distanceJson = HttpClientUtil.doGet("https://api.map.baidu.com/direction/v2/riding", mapRiding);
        JSONObject distanceJsonObject = JSONObject.parseObject(distanceJson);
        Integer status = distanceJsonObject.getInteger("status");
        if (status != 0){
            throw new OrderBusinessException(MessageConstant.TOO_FAR_AWAY);
        }
        Integer distance = distanceJsonObject
                           .getJSONObject("result")
                           .getJSONArray("routes")
                           .getJSONObject(0)
                           .getInteger("distance");
        if (distance.compareTo(maxDistance) > 0){
            throw new OrderBusinessException(MessageConstant.TOO_FAR_AWAY);
        }

        // 向订单表插入一条数据
        Orders orders = BeanUtil.copyProperties(ordersSubmitDTO, Orders.class);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setPayStatus(Orders.UN_PAID);
        //orders.setUserName();
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        ordersMapper.insert(orders);

        // 向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = BeanUtil.copyProperties(shoppingCart, OrderDetail.class);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        orderDetailMapper.insertBatch(orderDetails);

        // 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 封装订单VO，返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber()).build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态、给商家端推送有新的订单消息
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        // 支付成功后向商家端推送来单提醒
        Map map = new HashMap();
        map.put("type", 1); // 类型1为来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "有新的订单来了");
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
        ordersMapper.update(orders);
    }

    /**
     * 分页查询登录用户的历史订单
     * @param page
     * @param pageSize
     * @param status
     * @param currentId
     * @return
     */
    @Override
    public PageResult getHistoryOrdersByUserId(Integer page, Integer pageSize, Integer status, Long currentId) {
        Long userId = BaseContext.getCurrentId();
        // 使用pageHelper插件开始分页
        PageHelper.startPage(page, pageSize);

        // 根据用户id和订单状态查询订单
        Page<Orders> ordersPage = ordersMapper.getByStatusAndUserId(status, userId);

        // 获取用户订单分页查询结果
        List<Orders> ordersList = ordersPage.getResult();

        // 封装OrderVO
        List<OrderVO> orderVOS = BeanUtil.copyToList(ordersList, OrderVO.class);

        // 查询订单详细信息
        if (ordersList != null && !ordersList.isEmpty()){
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderIds(ordersList.stream().map(Orders::getId).collect(Collectors.toList()));
            // 将订单信息按照订单id分组
            Map<Long, List<OrderDetail>> orderId2OrderDetailsMap = orderDetails.stream().collect(Collectors.groupingBy(OrderDetail::getOrderId));

            // 设置orderVO的订单详细信息列表以及订单菜品信息
            orderVOS.forEach(orderVO -> {
                orderVO.setOrderDishes("");
                orderVO.setOrderDetailList(orderId2OrderDetailsMap.get(orderVO.getId()));
            });
        }

        PageResult pageResult = new PageResult(ordersPage.getTotal(), orderVOS);
        return pageResult;
    }

    /**
     * 根据订单id查询订单详细信息
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailById(Long id) {
        // 查询订单表
        Orders orders = ordersMapper.getById(id);

        // 查询订单详细信息表
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderIds(List.of(orders.getId()));

        // 封装VO，返回结果
        OrderVO orderVO = BeanUtil.copyProperties(orders, OrderVO.class);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancelOrderById(Long id) throws Exception {
        // 查询当前订单，如果订单状态已取消则不能取消
        Orders orderDB = ordersMapper.getById(id);
        if (orderDB == null || orderDB.getStatus().equals(Orders.CANCELLED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 如果订单支付状态为已付款，则为用户退款
        Integer payStatus = orderDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)){
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orderDB.getNumber(),
                    orderDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 更新订单状态为已取消
        ordersMapper.batchCancelOrdersByIds(List.of(id), Orders.CANCELLED, LocalDateTime.now(), "用户手动取消");
    }

    /**
     * 再来一单，将当前订单中的菜品或套餐加入购物车
     * @param id
     */
    @Override
    public void repetitionById(Long id) {
        // 根据订单id获取当前订单包含的菜品或套餐
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderIds(List.of(id));

        // 属性拷贝到购物车对象
        List<ShoppingCart> shoppingCarts = BeanUtil.copyToList(orderDetails, ShoppingCart.class);
        shoppingCarts.forEach(shoppingCart -> {
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
        });

        // 插入购物车表
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 商家端分页条件查询所有订单信息
     * @param beginTime
     * @param endTime
     * @param number
     * @param page
     * @param pageSize
     * @param phone
     * @param status
     * @return
     */
    @Override
    public PageResult pageConditionSearch(LocalDateTime beginTime, LocalDateTime endTime, String number, Integer page, Integer pageSize, String phone, Integer status) {
        // 使用pageHelper插件开始分页
        PageHelper.startPage(page, pageSize);
        Page<Orders> ordersPage = ordersMapper.pageConditionSearch(beginTime, endTime, number, phone, status);

        PageResult pageResult = new PageResult(ordersPage.getTotal(), ordersPage.getResult());
        return pageResult;
    }

    /**
     * 统计待派送、派送中、待接单状态订单的数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer confirmed = ordersMapper.countOrderByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countOrderByStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = ordersMapper.countOrderByStatus(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancelOrderByIdAndWithReason(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 查询当前订单支付状态，如果当前订单处于待处理和已取消状态则不能取消，取消订单时需要为已付款用户退款
        Orders ordersDB = ordersMapper.getById(ordersCancelDTO.getId());
        if (ordersDB == null || ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED) || ordersDB.getStatus().equals(Orders.CANCELLED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)){
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 设置订单状态为已取消
        Orders orders = BeanUtil.copyProperties(ordersCancelDTO, Orders.class);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(orders.getCancelReason());
        ordersMapper.update(orders);
    }

    /**
     * 商家接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrderById(OrdersConfirmDTO ordersConfirmDTO) {
        // 查询当前订单状态，只有状态为待接单才可以接单
        Orders ordersDB = ordersMapper.getById(ordersConfirmDTO.getId());

        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 设置订单状态为已接单
        Orders orders = BeanUtil.copyProperties(ordersConfirmDTO, Orders.class);
        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.update(orders);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrderById(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 查询当前订单状态，只有状态为待接单才可以拒单
        Orders ordersDB = ordersMapper.getById(ordersRejectionDTO.getId());
        Integer status = ordersDB.getStatus();
        if (ordersDB == null || !status.equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 拒单后为已付款用户退款
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)){
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 设置订单状态为已取消
        Orders orders = BeanUtil.copyProperties(ordersRejectionDTO, Orders.class);
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 商家派送订单
     * @param id
     */
    @Override
    public void deliveryOrderById(Long id) {
        // 判断当前订单的状态，只有待派送状态才能派送
        Orders ordersDB = ordersMapper.getById(id);
        Integer status = ordersDB.getStatus();
        if (ordersDB == null || !status.equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 设置订单状态为派送中
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS).build();
        ordersMapper.update(orders);
    }

    /**
     * 商家完成订单
     * @param id
     */
    @Override
    public void completeOrderById(Long id) {
        // 判断当前订单的状态，只有派送中状态才能设置为已完成
        Orders ordersDB = ordersMapper.getById(id);
        Integer status = ordersDB.getStatus();
        if (ordersDB == null || !status.equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 设置订单状态为已完成
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminderById(Long id) {
        // 判断当前订单是否存在以及是否处于待接单状态
        Orders orderDB = ordersMapper.getById(id);
        if (orderDB == null || !orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 用户催单后向商家端推送消息
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orderDB.getId());
        map.put("content", "有用户催单了");
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}